/**
 * ============================================
 * 本地有约 - API请求封装
 * 基于 Axios 的异步请求工具
 * ============================================
 */

// 配置 axios 默认值
axios.defaults.baseURL = window.location.origin;
axios.defaults.timeout = 10000;
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

// 从 cookie 中获取 CSRF token
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// 设置 CSRF token
const csrftoken = getCookie('csrftoken');
if (csrftoken) {
    axios.defaults.headers.common['X-CSRFToken'] = csrftoken;
}

// 请求拦截器
axios.interceptors.request.use(
    config => {
        // 显示加载状态
        showLoading();
        return config;
    },
    error => {
        hideLoading();
        return Promise.reject(error);
    }
);

// 响应拦截器
axios.interceptors.response.use(
    response => {
        hideLoading();
        return response;
    },
    error => {
        hideLoading();
        // 统一错误处理
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    showError('请先登录');
                    setTimeout(() => {
                        window.location.href = '/users/login/';
                    }, 1500);
                    break;
                case 403:
                    showError('没有权限执行此操作');
                    break;
                case 404:
                    showError('请求的资源不存在');
                    break;
                case 500:
                    showError('服务器错误，请稍后重试');
                    break;
                default:
                    showError(error.response.data.message || '请求失败');
            }
        } else {
            showError('网络错误，请检查网络连接');
        }
        return Promise.reject(error);
    }
);

/**
 * ============================================
 * API 接口封装
 * ============================================
 */

const API = {
    // ========== 用户相关 ==========
    users: {
        // 登录
        login: (data) => axios.post('/users/login/', data),
        
        // 注册
        register: (data) => axios.post('/users/register/', data),
        
        // 发送验证码（支持邮箱）
        sendCode: (data) => axios.post('/users/api/send-code/', data),
        
        // 获取用户信息
        getProfile: (userId) => axios.get(`/users/profile/${userId}/`),
        
        // 更新用户信息
        updateProfile: (userId, data) => axios.put(`/users/api/${userId}/`, data),
        
        // 关注用户
        follow: (userId) => axios.post(`/users/api/${userId}/follow/`),
        
        // 取消关注
        unfollow: (userId) => axios.post(`/users/api/${userId}/unfollow/`),
        
        // 获取关注列表
        getFollowing: (userId) => axios.get(`/users/api/${userId}/following/`),
        
        // 获取粉丝列表
        getFollowers: (userId) => axios.get(`/users/api/${userId}/followers/`),
        
        // 更新隐私设置
        updatePrivacy: (data) => axios.post('/users/api/privacy/', data),
    },

    // ========== 活动相关 ==========
    activities: {
        // 获取活动列表
        getList: (params) => axios.get('/activities/api/list/', { params }),
        
        // 获取活动详情
        getDetail: (activityId) => axios.get(`/activities/api/${activityId}/`),
        
        // 创建活动
        create: (data) => axios.post('/activities/api/create/', data),
        
        // 上传活动图片
        uploadImage: (file, onProgress) => {
            const formData = new FormData();
            formData.append('image', file);
            return axios.post('/activities/api/upload-image/', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                },
                onUploadProgress: progressEvent => {
                    if (onProgress) {
                        const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                        onProgress(percentCompleted);
                    }
                }
            });
        },
        
        // 更新活动
        update: (activityId, data) => axios.put(`/activities/api/${activityId}/`, data),
        
        // 删除活动
        delete: (activityId) => axios.delete(`/activities/api/${activityId}/`),
        
        // 报名活动
        register: (activityId, data) => axios.post(`/activities/api/${activityId}/register/`, data),
        
        // 取消报名
        cancelRegistration: (activityId) => axios.post(`/activities/api/${activityId}/cancel/`, data),
        
        // 签到
        checkIn: (activityId, data) => axios.post(`/activities/api/${activityId}/checkin/`, data),
        
        // 获取活动类型
        getTypes: () => axios.get('/activities/api/types/'),
        
        // 搜索活动
        search: (keyword) => axios.get('/activities/api/list/', { params: { search: keyword } }),
    },

    // ========== 评论相关 ==========
    comments: {
        // 获取评论列表
        getList: (activityId, params) => axios.get(`/social/api/activities/${activityId}/comments/`, { params }),
        
        // 发表评论
        create: (activityId, data) => axios.post(`/social/api/activities/${activityId}/comments/create/`, data),
        
        // 删除评论
        delete: (commentId) => axios.delete(`/social/api/comments/${commentId}/delete/`),
        
        // 点赞评论
        like: (commentId) => axios.post(`/social/api/comments/${commentId}/like/`),
        
        // 取消点赞
        unlike: (commentId) => axios.post(`/social/api/comments/${commentId}/unlike/`),
    },

    // ========== 评分相关 ==========
    ratings: {
        // 提交评分
        create: (activityId, data) => axios.post(`/social/api/activities/${activityId}/ratings/create/`, data),
        
        // 获取评分
        get: (activityId) => axios.get(`/social/api/activities/${activityId}/ratings/`),
    },

    // ========== 积分相关 ==========
    points: {
        // 获取积分记录
        getRecords: (params) => axios.get('/points/api/records/', { params }),
        
        // 获取积分商品
        getProducts: (params) => axios.get('/points/api/products/', { params }),
        
        // 兑换商品
        exchange: (productId, data) => axios.post(`/points/api/products/${productId}/exchange/`, data),
        
        // 获取兑换记录
        getExchanges: () => axios.get('/points/api/exchanges/'),
    },

    // ========== 通知相关 ==========
    notifications: {
        // 获取通知列表
        getList: (params) => axios.get('/notifications/api/list/', { params }),
        
        // 标记为已读
        markAsRead: (notificationId) => axios.post(`/notifications/api/${notificationId}/read/`),
        
        // 全部标记为已读
        markAllAsRead: () => axios.post('/notifications/api/read-all/'),
        
        // 获取未读数量
        getUnreadCount: () => axios.get('/notifications/api/unread-count/'),
    },

    // ========== 推荐系统 ==========
    recommendations: {
        // 获取推荐活动
        getActivities: (params) => axios.get('/recommendations/api/activities/', { params }),
        
        // 记录浏览行为
        recordView: (activityId, data) => axios.post(`/recommendations/api/activities/${activityId}/view/`, data),
    },

    // ========== 文件上传 ==========
    upload: {
        // 上传图片
        image: (file, onProgress) => {
            const formData = new FormData();
            formData.append('file', file);
            return axios.post('/api/upload/image/', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                },
                onUploadProgress: progressEvent => {
                    if (onProgress) {
                        const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                        onProgress(percentCompleted);
                    }
                }
            });
        },
    }
};

/**
 * ============================================
 * 工具函数
 * ============================================
 */

// 显示加载状态
let loadingCount = 0;
function showLoading() {
    loadingCount++;
    if (loadingCount === 1) {
        const loader = document.getElementById('global-loader');
        if (loader) {
            loader.style.display = 'flex';
        }
    }
}

// 隐藏加载状态
function hideLoading() {
    loadingCount--;
    if (loadingCount === 0) {
        const loader = document.getElementById('global-loader');
        if (loader) {
            loader.style.display = 'none';
        }
    }
}

// 显示成功消息
function showSuccess(message) {
    showToast(message, 'success');
}

// 显示错误消息
function showError(message) {
    showToast(message, 'danger');
}

// 显示提示消息
function showToast(message, type = 'info') {
    const toastContainer = document.getElementById('toast-container');
    if (!toastContainer) {
        const container = document.createElement('div');
        container.id = 'toast-container';
        container.style.cssText = 'position: fixed; top: 20px; right: 20px; z-index: 9999;';
        document.body.appendChild(container);
    }
    
    const toast = document.createElement('div');
    toast.className = `alert alert-${type} alert-dismissible fade show`;
    toast.style.cssText = 'min-width: 300px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);';
    toast.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.getElementById('toast-container').appendChild(toast);
    
    setTimeout(() => {
        toast.remove();
    }, 3000);
}

// 确认对话框
function confirmAction(message, callback) {
    if (confirm(message)) {
        callback();
    }
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    const now = new Date();
    const diff = now - date;
    
    const minute = 60 * 1000;
    const hour = 60 * minute;
    const day = 24 * hour;
    
    if (diff < minute) {
        return '刚刚';
    } else if (diff < hour) {
        return Math.floor(diff / minute) + '分钟前';
    } else if (diff < day) {
        return Math.floor(diff / hour) + '小时前';
    } else if (diff < 7 * day) {
        return Math.floor(diff / day) + '天前';
    } else {
        return date.toLocaleDateString('zh-CN');
    }
}

// 格式化数字
function formatNumber(num) {
    if (num >= 10000) {
        return (num / 10000).toFixed(1) + '万';
    } else if (num >= 1000) {
        return (num / 1000).toFixed(1) + 'k';
    }
    return num;
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 节流函数
function throttle(func, limit) {
    let inThrottle;
    return function(...args) {
        if (!inThrottle) {
            func.apply(this, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}
